<?php
namespace App\Libs;

/**
 * 替代 curl_init post
 *
 * @author hyf
 *        
 */
class HttpServe
{

    public function __construct()
    {
        $this->ch = curl_init();
    }

    public function post($url, $postFields = null)
    {
        // 从京东的SDK copy过来的
        $ch = $this->ch;
        if (! app()->environment('production')) {
            curl_setopt($ch, CURLOPT_VERBOSE, 1); // 启用时会汇报所有的信息，存放在STDERR或指定的CURLOPT_STDERR中
        }
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if (isset($this->readTimeout)) {
            curl_setopt($ch, CURLOPT_TIMEOUT, $this->readTimeout);
        }
        if (isset($this->connectTimeout)) {
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->connectTimeout);
        }
        // https 请求
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == "https") {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        }
        
        if (is_array($postFields) && 0 < count($postFields)) {
            $postBodyString = "";
            $postMultipart = false;
            foreach ($postFields as $k => $v) {
                if ("@" != substr($v, 0, 1)) {  // 判断是不是文件上传
                    $postBodyString .= "$k=" . urlencode($v) . "&";
                } else { // 文件上传用multipart/form-data，否则用www-form-urlencoded
                    $postMultipart = true;
                }
            }
            unset($k, $v);
            curl_setopt($ch, CURLOPT_POST, true);
            if ($postMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, - 1));
            }
        }
        $reponse = curl_exec($ch);
        
        if (curl_errno($ch)) {
            throw new \Exception(curl_error($ch), 0);
        } else {
            $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            if (200 !== $httpStatusCode) {
                throw new \Exception($reponse, $httpStatusCode);
            }
        }
        curl_close($ch);
        return iconv('GBK','UTF-8', $reponse);
    }

    public function get()
    {}
}